import axios from 'axios'
import store from '@/store'
import { debounce } from 'throttle-debounce'

// 报错防抖处理
const errorDebounce = debounce(300, (message) => {
  uni.showToast({
    title: message,
    icon: 'none'
  })
})

class HttpRequest {
  constructor (baseUrl = baseUrl) {
    this.baseUrl = baseUrl
  }
  getInsideConfig () {
    const config = {
      baseURL: this.baseUrl,
      method: 'post',
      headers: {
      }
    }
    return config
  }
  // 请求拦截器
  interceptors (instance, url) {
    instance.interceptors.request.use(config => {
      const token = store.state.user.token || 1632361216136
      if (token) {
        config.url = `${config.url}?SID=${token}`
      }
      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(({ data }) => {
      const { code, errorMsg } = data
      if (code === 'OK') {
        return data
      } else if (code === 'NOT_LOGIN' || code === 'OTHER_LOGIN') {
        // store.dispatch('handleLogOut').then(() => {
        //   router.push('/login')
        // })
        errorDebounce(errorMsg)
        return Promise.reject(data)
      } else if (code === 'FIELD_ERROR') {
        for (let key in errorMsg) {
          uni.showToast({
            title: `${errorMsg[key]}`,
            icon: 'none'
          })
        }
        return Promise.reject(data)
      } else {
        uni.showToast({
          title: errorMsg,
          icon: 'none'
        })
        return Promise.reject(data)
      }
    }, error => {
      return Promise.reject(error)
    })
    instance.defaults.adapter = function(config) { //自己定义个适配器，用来适配uniapp的语法
      return new Promise((resolve, reject) => {
        // console.log(config)
        var settle = require('axios/lib/core/settle');
        var buildURL = require('axios/lib/helpers/buildURL');
        uni.request({
          method: config.method.toUpperCase(),
          url: config.baseURL + buildURL(config.url, config.params, config.paramsSerializer),
          header: config.headers,
          data: config.data,
          dataType: config.dataType,
          responseType: config.responseType,
          sslVerify: config.sslVerify,
          complete: function complete(response) {
            // console.log("执行完成：",response)
            response = {
              data: response.data,
              status: response.statusCode,
              errMsg: response.errMsg,
              header: response.header,
              config: config
            };
            settle(resolve, reject, response);
          }
        })
      })
  }
  }
  request (options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
}
export default HttpRequest